import { ecs } from "db://oops-framework/libs/ecs/ECS";
import { Role } from "../Role";
import { RoleAttributeType, RoleModuleType } from "../model/RoleEnum";
import { oops } from "db://oops-framework/core/Oops";
import { smc } from "../../common/ecs/SingletonModuleComp";
import { RoleEvent } from "../RoleEvent";

/**
 * 星星升级
 */
@ecs.register('RoleStarUp')
export class RoleStarUpComp extends ecs.Comp {
    /** 星星 */
    star: number = 0;

    /** 0:设置默认星星，1:升星*/
    type: number = 0;

    reset() {
        this.star = 1;
        this.type = 0;
    }
}
export class RoleStarUpSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
    filter(): ecs.IMatcher {
        return ecs.allOf(RoleStarUpComp);
    }

    entityEnter(e: Role): void {
        let rm = e.RoleModel;
        let ru = e.RoleStarUp;
        let rms = e.RoleModelStar;
        if (ru.type == 0) {
            this.setAttr(e, ru.star);
        }
        else {
            // 升星
            if (!rms.canUp) {
                oops.gui.toast("碎片不足");
                e.remove(RoleStarUpComp);
                return
            }
            this.levelUp(e);
        }
    }
    private levelUp(e: Role) {
        let rm = e.RoleModel;

        var params: any = {
            heroid: rm.id,
        }

        let rms = e.RoleModelStar;
        let star = e.RoleStarUp.star
        let onComplete = {
            target: this,
            callback: (data: any) => {
                rms.bfAtk = e.atk;
                rms.bfDef = e.def;
                rms.bfHp = e.hp;
                rms.bfSpd = e.spd;
                smc.account.addItem(e.RoleModel.clipId, -e.RoleModelStar.nextCurrent.cost_clip_num);
                this.setAttr(e, star);
                e.loadStarUpSuccessPop();
                setTimeout(() => {
                    oops.message.dispatchEvent(RoleEvent.RoleStarUp);
                }, 200);
                e.checkBookStar();
            }
        }
        //  netChannel.game.req("user", "starup", params, onComplete);
        onComplete.callback(null);
        e.remove(RoleStarUpComp);
    }

    private setAttr(e: Role, star: number) {
        let rm = e.RoleModel;

        if (star) {
            const starCurrent = e.RoleModelStar.starCurrent;
            starCurrent.init(star);
            e.setNumericValue(RoleAttributeType.def_ratio, RoleModuleType.Star, starCurrent.def_ratio);
            e.setNumericValue(RoleAttributeType.atk_ratio, RoleModuleType.Star, starCurrent.atk_ratio);
            e.setNumericValue(RoleAttributeType.hp_ratio, RoleModuleType.Star, starCurrent.hp_ratio);
        }

        rm.star = star;
        e.RoleModelStar.nextCurrent.init(Math.min(star + 1, 30));

        e.remove(RoleStarUpComp);
    }
}